package com.chen.controller;

import com.chen.bean.Result;
import com.chen.service.UserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@CrossOrigin
public class PictureController {

    @Resource
    UserService userService;

    @PostMapping("/uploadImg")
    public Result imgUpload(@RequestParam("picture") MultipartFile picture, HttpServletRequest request) {
        String path = request.getSession().getServletContext().getRealPath("/upload");
        File filePath = new File(path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            System.out.println("目录不存在");
            filePath.mkdir();
        }
        String originalFilename = picture.getOriginalFilename();

        //获取文件类型，以最后一个`.`为标识
        String type = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //获取文件名称（不包含格式）
        String name = originalFilename.substring(0, originalFilename.lastIndexOf("."));

        //设置文件新名称: 当前时间+文件名称（不包含格式）
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(d);
        String newFileName = date + "." + type;

        //在指定路径下创建一个文件
        File targetFile = new File(path, newFileName);
        //将文件保存到服务器指定位置

        String url="http://localhost:9091/blog/upload/"+newFileName;
        String username = request.getParameter("username");

        userService.addAvatar(url,username);

        try {
            picture.transferTo(targetFile);
            //将文件在服务器的存储路径返回
            return Result.success(url);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(1, "上传失败", null);
        }
    }
}
